package com.example.juyixia;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.crypto.Cipher;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import com.example.adapter.ChatMsgViewAdapter;
import com.example.database.DbManager;
import com.example.mathutil.RSACoder;
import com.exanple.data.ChatMsgEntity;
import com.exanple.data.Messageinfo;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources.NotFoundException;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class Activity_chatActivity extends Activity {
	private Button bback;
	private String sendip;
	private Button bsend;
	private ChatMsgViewAdapter cvadapter;
	private EditText messContent;
	 private DbManager mgr; 
	private Myinfo myinfo;
	private Handler handler1;
    private String recname;
    private ListView messentylist;
	public static final String bm="utf-8";
	private String publickey;
    private List<ChatMsgEntity> chatentys=new ArrayList<ChatMsgEntity>();
    private JSONObject messjson;
    private static final String TAG="TestTag";
    private boolean havemess;
    //注册广播接受
    public static final String ACTION_UPDATEUI = "action.updateUI";  
    UpdateUIBroadcastReceiver broadcastReceiver;
    

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		myinfo=(Myinfo)getApplication();
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_chat);
		TextView currentfriend = (TextView) findViewById(R.id.currentfriend);
		messContent = (EditText) findViewById(R.id.et_sendmessage);
		messentylist=(ListView) findViewById(R.id.messEntylist);
		mgr = new DbManager(this);
		//动态注册广播		
        IntentFilter filter = new IntentFilter();  
        filter.addAction(ACTION_UPDATEUI);  
        broadcastReceiver = new UpdateUIBroadcastReceiver();  
        registerReceiver(broadcastReceiver, filter);
        
		Intent intent = getIntent();
		Bundle bundle = intent.getExtras();
		if (bundle != null) {
			recname=bundle.get("name").toString();
			currentfriend.setText(recname);
			sendip = bundle.getString("ip").toString();
			publickey=bundle.getString("publickey").toString();
		}
		chatentys=mgr.query(myinfo.getUsername(),recname);
		  cvadapter=new ChatMsgViewAdapter(this,chatentys,myinfo.getUsername());
		  messentylist.setAdapter(cvadapter);		     
		  bsend = (Button) findViewById(R.id.mess_send);
		  bsend.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub    	
				ChatMsgEntity thisenty=new ChatMsgEntity(myinfo.getUsername(),recname,getDate(),messContent.getText().toString());    
				
				 for (Messageinfo mess : Messageinfo.messlist) {
						if(mess.getSendname().equals(thisenty.getRecname())){
							mess.setMesscontent(thisenty.getMesscontent());					
							havemess=true;
						}
					}
				 if(!havemess){
					 Messageinfo.messlist.add(new Messageinfo(thisenty.getRecname(), thisenty.getSendname(), thisenty.getMesscontent(), thisenty.getSendtime(), publickey, sendip));
				 }
				chatentys.add(thisenty);		           	              

					Map<String, String> encryptmessmap=new HashMap<String, String>();
					
					try {
						byte [] code=RSACoder.encryptByPublicKey(thisenty.getMesscontent().getBytes(), publickey);
				
						BASE64Encoder enc=new BASE64Encoder();
						String mes=enc.encodeBuffer(code); //使用BASE64编码
						encryptmessmap.put("发送人", thisenty.getSendname());
						encryptmessmap.put("接收人", thisenty.getRecname());
						encryptmessmap.put("发送时间", thisenty.getSendtime());
						encryptmessmap.put("消息内容", mes);
						encryptmessmap.put("publickey", myinfo.getPublickey());
						encryptmessmap.put("ip", myinfo.getUserip());
						messjson=new JSONObject(encryptmessmap);
					} catch (Exception e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					
				new Thread() {
					public void run() {	
						
			             
						Socket socket = null;
						try {
							socket = new Socket(sendip, 36363); // IP一定是本地机器的ip

							
							PrintWriter out = new PrintWriter(
									new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),bm)), true);
							out.println(messjson.toString());						
							out.close();
							socket.close();
							
							
						} catch (Exception e) {

						}

						handler.sendEmptyMessage(0);// 执行完毕后给handler发送一个空消息
					}

					// 定义Handler对象
					private Handler handler = new Handler() {
						@Override
						// 当有消息发送出来的时候就执行Handler的这个方法
						public void handleMessage(Message msg) {
							super.handleMessage(msg);
							// 处理UI
							System.out.println("OK?");
						}
					};
				}.start();
				 mgr.add(thisenty);
	             cvadapter.notifyDataSetChanged(); 			
	 			messContent.setText("");	
	 			messentylist.setSelection(messentylist.getCount() - 1);
			}
		});
		bback = (Button) findViewById(R.id.mess_back);
		bback.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mgr.deleteData();
				finish();
			}
		});
	}
	
	 private class UpdateUIBroadcastReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context arg0, Intent arg1) {
			// TODO Auto-generated method stub
			chatentys=mgr.query(myinfo.getUsername(),recname);
			  cvadapter=new ChatMsgViewAdapter(arg0,chatentys,myinfo.getUsername());
			  messentylist.setAdapter(cvadapter);

		}  
		  
	        
	  
	    }  
	 private String getDate() {
	        Calendar c = Calendar.getInstance();
	        String year = String.valueOf(c.get(Calendar.YEAR));
	        String month = String.valueOf(c.get(Calendar.MONTH)+1);
	        String day = String.valueOf(c.get(Calendar.DAY_OF_MONTH));
	        String hour = String.valueOf(c.get(Calendar.HOUR_OF_DAY));
	        String mins = String.valueOf(c.get(Calendar.MINUTE));
	     
	        StringBuffer sbBuffer = new StringBuffer();
	        sbBuffer.append(year + "-" + month + "-" + day + " " + hour + ":" + mins); 						
	      						
	        return sbBuffer.toString();
	    }
	 @Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		// 注销广播  
        unregisterReceiver(broadcastReceiver);
	}

	 
}
